package com.example.demoshiro.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.democommon.contasant.CommonConstant;
import com.example.democommon.tools.PasswordUtil;
import com.example.democommon.tools.Result;
import com.example.demodao.entity.SysUser;
import com.example.demoshiro.tools.JwtUtil;
import com.example.demoshiro.tools.RedisUtil;
import com.example.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>
 * Index
 * </p>
 *
 * @author ross zhang
 * @version 1.0
 * @PackageName demo-one
 * @Package com.example.demoshiro.controller
 * @since 2022/4/16 15:18
 */
@RestController
@Slf4j
public class IndexController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserService sysUserService;

    @GetMapping
    public ModelAndView query(ModelAndView modelAndView) {
        modelAndView.addObject("success", "我是整合shiro用的哦！！！");
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * @param username, password
     * @return com.example.democommon.tools.Result<?>
     * @description: 模拟用户登录
     * @author rosszhang
     * @date 2022-04-16 13:49
     */
    @PostMapping("/login")
    public Result<?> login(@RequestParam(name = "username") String username,
                           @RequestParam(name = "password") String password) {
        // 获取用户部门信息
        JSONObject obj = new JSONObject();

        //1、验证用户是否存在
        SysUser sysUser = this.sysUserService.selectByUsername(username);
        if (null == sysUser) {
            return Result.error("用户不存在");
        }
        //2、校验密码
        String userPwd = PasswordUtil.encrypt(username, password, sysUser.getSalt());
        if (!userPwd.equals(sysUser.getPassword())) {
            return new Result<>().error500("用户名或密码错误");
        }

        // 3、生成Token
        String token = JwtUtil.sign(username, sysUser.getPassword());
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + username, token, CommonConstant.TOKEN_EXPIRE_TIME);
        obj.put("token", token);
        obj.put("userInfo", sysUser);
        return Result.OK("登录成功", obj);
    }

    @GetMapping("/test")
    public Result test() {
        System.out.println("进入测试，只有带有令牌才可以进入该方法");
        return Result.OK("访问接口成功");
    }

}
